using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Zhao.IServer.Management_Arena;
using Zhao.IServer.Field;
using Zhao.Models.DTO;
using Zhao.Models.AppletDto;
using Zhao.Models.Entity;
using Zhao.Common.Helper;
using Microsoft.AspNetCore.Mvc.Formatters;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Zhao.IServer;
using Quartz.Simpl;
using System.Security.Cryptography;
using Zhao.Common;
using Zhao.IServer.User;

namespace Zhao.Arena.MiniProgram.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class VenueController : ControllerBase
    {
        private readonly IVenuesServer _venuesServer;
        private readonly IVenuesImageService _venuesImageService;
        private readonly IFieldsServer _fieldsServer;
        private readonly IAreaServer _areaServer;
        private readonly IVenueApplicationsServer _venueApplicationsServer;
        private readonly IAdminServer _adminServer;

        public VenueController(
            IVenuesServer venuesServer, 
            IVenuesImageService venuesImageService,
            IFieldsServer fieldsServer,
            IVenueApplicationsServer venueApplicationsServer,
            IAreaServer areaServer,
            IAdminServer adminServer)
        {
            _venuesServer = venuesServer;
            _venuesImageService = venuesImageService;
            _fieldsServer = fieldsServer;
            _venueApplicationsServer = venueApplicationsServer;
            _areaServer = areaServer;
            _adminServer = adminServer;
        }

        /// <summary>
        /// 获取球馆列表（支持多条件查询）
        /// </summary>
        /// <param name="city">城市ID</param>
        /// <param name="area">区域ID</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页大小</param>
        /// <param name="searchString">搜索关键词</param>
        /// <returns>球馆列表</returns>
        [HttpGet]
        [Route("{pageIndex:int}/{pageSize:int}")]
        [Route("{pageIndex:int}/{pageSize:int}/{city:int}")]
        [Route("{pageIndex:int}/{pageSize:int}/{city:int}/{area:int}")]
        [Route("{pageIndex:int}/{pageSize:int}/{city:int}/{searchString}")]
        [Route("{pageIndex:int}/{pageSize:int}/{city:int}/{area:int}/{searchString}")]
        public async Task<JsonResult> GetVenues(int city = 0, int area = 0, int pageIndex = 1, int pageSize = 10, string searchString = "")
        {
            Expressionable<Venues> expressionable = new Expressionable<Venues>();

            // 添加搜索条件
            expressionable.AndIF(!searchString.IsNullOrWhiteSpace(), (a) => a.VenueName.Contains(searchString) || a.Address.Contains(searchString));

            // 添加城市筛选
            expressionable.AndIF(city != 0, (a) => a.City == city);

            // 添加区域筛选
            expressionable.AndIF(area != 0, (a) => a.Zone == area);

            // 只查询正常营业的球馆
            expressionable.And((a) => a.IsDeleted == 1);

            var result = await _venuesServer.GetVenueInfo(expressionable.ToExpression(), pageIndex, pageSize);

            return new JsonResult(result);
        }

        /// <summary>
        /// 获取球馆场地类型和未来一周价格
        /// </summary>
        /// <param name="venueId">球馆ID</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页大小</param>
        /// <returns>场地类型和价格信息</returns>
        [HttpGet]
        [Route("fields/{venueId}")]
        [Route("fields/{venueId}/{pageIndex:int}/{pageSize:int}")]
        public async Task<JsonResult> GetVenueFields(Guid venueId, int pageIndex = 1, int pageSize = 10)
        {
            if (venueId == Guid.Empty)
            {
                return new JsonResult(new { code = -1, msg = "参数无效" });
            }

            var venue = await _venuesServer.QueryAsync(x => x.VenueID == venueId);

            if (venue == null)
            {
                return new JsonResult(new { code = -1, msg = "球馆不存在" });
            }

            var result = await _fieldsServer.GetVenueFieldsInfo(venueId, pageIndex, pageSize);
            return new JsonResult(result);
        }

        /// <summary>
        /// 获取球馆详情（包含详情图片、预定规则、场馆详情）
        /// </summary>
        /// <param name="venueId">球馆ID</param>
        /// <returns>球馆详情</returns>
        [HttpGet]
        [Route("detail/{venueId}")]
        public async Task<JsonResult> GetVenueDetail(Guid venueId)
        {
            var result = new ApiResult<VenuesDetailsInfoDto>
            {
                Success=false
            };

            if (venueId == default)
            {
                result.Message = "参数无效";
                return new JsonResult(result);
            }

            var venue = await _venuesServer.QueryAsync(x => x.VenueID == venueId);

            if (venue == null)
            {
                result.Message = "球馆不存在";
                return new JsonResult(result);
            }

            // 构建表达式，按ID查询
            Expressionable<Venues, Area, Area, Area> expression = new Expressionable<Venues, Area, Area, Area>();

            expression.And((a, b, c, d) => a.VenueID == venueId && a.IsDeleted == 1);

            result.Data = await _venuesServer.GetVenuesById(expression.ToExpression());
            if (result.Data != null)
            {
                result.Message = "成功";
                result.Success = true;
            }

            else result.Message = "为查询到数据";


            return new JsonResult(result);
        }



        /// <summary>
        /// 获取球馆营业时间
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("{venuId}")]
        public async Task<JsonResult> GetBusiness(Guid venuId)
        {
            var result = new ApiResult<VenuesTimeDto>() { Success = false, Message = "操作失败" };

            if (venuId == default)
            {
                result.Message = "缺少必要参数";
                return new JsonResult(result);
            }

            Expressionable<Venues> expressionable = new Expressionable<Venues>();

            expressionable.And(a => a.VenueID == venuId);

            var data = await _venuesServer.QueryAsync(expressionable.ToExpression());

            if (data != null)
            {
                result.Data = new VenuesTimeDto
                {
                    OpenTime = data.OpenTime,
                    CloseTime = data.CloseTime,
                };
                result.Success = true;
                result.Message = "操作成功";
            }

            return new JsonResult(result);

        }

        /// <summary>
        /// 小程序端提交球馆入驻申请
        /// </summary>
        [HttpPost("apply")]
        [Authorize] //需要登录验证
        public async Task<JsonResult> ApplyVenue([FromBody] VenueApplicationCreateDto dto)
        {
            var result = new ApiResult { Success = false };
            // 手动校验所有字段
            var errors = new List<string>();
            if (dto.VenueName.IsNullOrWhiteSpace())
            {
                result.Message = "球馆名称不能为空";
                return new JsonResult(result);
            }

            if (dto.Address.IsNullOrWhiteSpace())
            {
                result.Message = "详细地址不能为空";
                return new JsonResult(result);
            }

            if (dto.LicenseImage.IsNullOrWhiteSpace())
            {
                result.Message = "请上传营业执照图片";
                return new JsonResult(result);
            }

            if (dto.Images.IsNullOrWhiteSpace())
            {
                result.Message = "请上传球馆门口招牌图片";
                return new JsonResult(result);
            }

            if (dto.Images.IsNullOrWhiteSpace())
            {
                result.Message = "请上传球馆照片";
                return new JsonResult(result);
            }

            if(dto.ContactPhone.IsNullOrWhiteSpace() || !dto.ContactPhone.IsMobileNumber())
            {
                result.Message = "手机号为空或格式错误";
                return new JsonResult(result);
            }

            // 校验省市区层级关系
            bool areaValid =  _areaServer.ValidateAreaHierarchy(dto.Province, dto.City, dto.Zone);
            if (!areaValid)
            {
                result.Message = "省/市/区选择不合法，请重新选择";
                return new JsonResult(result);
            }

            string? idClaim = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Sid))?.Value;
            if (idClaim.IsNullOrWhiteSpace())
            {
                result.Message = "无权限，请登录";
                return new JsonResult(result);
            }
            int userId = (int)idClaim.ToInt32();
            // DTO转实体
            var application = new VenueApplications
            {
                VenueName = dto.VenueName,
                Address = dto.Address,
                Images = dto.Images,
                ContactPhone = dto.ContactPhone,
                Description = dto.Description,
                ManagerName = dto.ManagerName,
                Province = dto.Province,
                City = dto.City,
                Zone = dto.Zone,
                CreatedByUserID = userId,
                License=dto.LicenseImage
            };
            result = await _venueApplicationsServer.AddVenueApplicationAsync(application);
            return new JsonResult(result);
        }

        /// <summary>
        /// 查询用户是否已提交过球馆入驻申请
        /// </summary>
        [HttpGet("check-application")]
        [Authorize]
        public async Task<JsonResult> CheckUserApplication()
        {
            // 从Token中获取用户ID
            string? idClaim = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Sid))?.Value;
            if (idClaim.IsNullOrWhiteSpace())
            {
                return new JsonResult(new ApiResult { Success = false, Message = "无权限，请登录" });
            }
            int userId = (int)idClaim.ToInt32();
            
            // 调用服务查询用户申请记录
            var result = await _venueApplicationsServer.CheckUserApplicationAsync(userId);
            return new JsonResult(result);
        }

        /// <summary>
        /// 查询用户申请状态
        /// </summary>
        [HttpGet("application-status")]
        [Authorize]
        public async Task<JsonResult> GetApplicationStatus()
        {
            // 从Token中获取用户ID
            string? idClaim = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Sid))?.Value;
            if (idClaim.IsNullOrWhiteSpace())
            {
                return new JsonResult(new ApiResult<int> { Success = false, Message = "无权限，请登录", Data = 0 });
            }
            int userId = (int)idClaim.ToInt32();
            
            // 调用服务查询用户申请状态
            var result = await _venueApplicationsServer.GetUserApplicationStatusAsync(userId);
            return new JsonResult(result);
        }

        /// <summary>
        /// 重新提交球馆入驻申请
        /// </summary>
        [HttpPost("reapply")]
        [Authorize]
        public async Task<JsonResult> ReapplyVenue([FromBody] VenueApplicationCreateDto dto)
        {
            var result = new ApiResult { Success = false };
            
            // 验证ApplicationID是否存在
            if (!dto.ApplicationID.HasValue || dto.ApplicationID <= 0)
            {
                result.Message = "申请ID不能为空";
                return new JsonResult(result);
            }
            
            // 手动校验所有字段
            if (dto.VenueName.IsNullOrWhiteSpace())
            {
                result.Message = "球馆名称不能为空";
                return new JsonResult(result);
            }

            if (dto.Address.IsNullOrWhiteSpace())
            {
                result.Message = "详细地址不能为空";
                return new JsonResult(result);
            }

            if (dto.LicenseImage.IsNullOrWhiteSpace())
            {
                result.Message = "请上传营业执照图片";
                return new JsonResult(result);
            }

            if (dto.Images.IsNullOrWhiteSpace())
            {
                result.Message = "请上传球馆照片";
                return new JsonResult(result);
            }

            if(dto.ContactPhone.IsNullOrWhiteSpace() || !dto.ContactPhone.IsMobileNumber())
            {
                result.Message = "手机号为空或格式错误";
                return new JsonResult(result);
            }

            // 校验省市区层级关系
            bool areaValid =  _areaServer.ValidateAreaHierarchy(dto.Province, dto.City, dto.Zone);
            if (!areaValid)
            {
                result.Message = "省/市/区选择不合法，请重新选择";
                return new JsonResult(result);
            }

            string? idClaim = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Sid))?.Value;
            if (idClaim.IsNullOrWhiteSpace())
            {
                result.Message = "无权限，请登录";
                return new JsonResult(result);
            }
            int userId = (int)idClaim.ToInt32();
            
            // DTO转实体
            var application = new VenueApplications
            {
                VenueName = dto.VenueName,
                Address = dto.Address,
                Images = dto.Images,
                ContactPhone = dto.ContactPhone,
                Description = dto.Description,
                ManagerName = dto.ManagerName,
                Province = dto.Province,
                City = dto.City,
                Zone = dto.Zone,
                CreatedByUserID = userId,
                License = dto.LicenseImage
            };
            
            // 调用重新申请方法
            result = await _venueApplicationsServer.ReapplyVenueApplicationAsync(dto.ApplicationID.Value, application);
            return new JsonResult(result);
        }
        
        /// <summary>
        /// 球馆账号开通与设置
        /// </summary>
        [HttpPost("setup-account")]
        [Authorize]
        public async Task<JsonResult> SetupVenueAccount([FromBody] VenueAccountSetupDto dto)
        {
            var result = new ApiResult { Success = false };
            
            // 验证必填字段
            if (dto.VenueID == Guid.Empty)
            {
                result.Message = "球馆ID不能为空";
                return new JsonResult(result);
            }
            
            if (dto.ReservationRules.IsNullOrWhiteSpace())
            {
                result.Message = "预定规则不能为空";
                return new JsonResult(result);
            }
            
            if (dto.Phone.IsNullOrWhiteSpace() || !dto.Phone.IsMobileNumber())
            {
                result.Message = "联系电话为空或格式错误";
                return new JsonResult(result);
            }

            // 验证新增管理员必填字段
            if (dto.UserName.IsNullOrWhiteSpace())
            {
                result.Message = "管理员用户名不能为空";
                return new JsonResult(result);
            }
            
            if (dto.Password.IsNullOrWhiteSpace())
            {
                result.Message = "管理员密码不能为空";
                return new JsonResult(result);
            }
            
            if (dto.Email.IsNullOrWhiteSpace())
            {
                result.Message = "管理员邮箱不能为空";
                return new JsonResult(result);
            }
            
            string? idClaim = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Sid))?.Value;
            if (idClaim.IsNullOrWhiteSpace())
            {
                result.Message = "无权限，请登录";
                return new JsonResult(result);
            }
            int userId = (int)idClaim.ToInt32();
            
            // 查询球馆是否存在
            var venue = await _venuesServer.QueryAsync(v => v.VenueID == dto.VenueID);
            if (venue == null)
            {
                result.Message = "球馆不存在";
                return new JsonResult(result);
            }
            
            // 查询与该球馆ID关联的申请记录
            var application = await _venueApplicationsServer.QueryAsync(a => a.VenunId == dto.VenueID);
            if (application == null)
            {
                result.Message = "未找到关联的申请记录";
                return new JsonResult(result);
            }
            
            // 检查申请状态是否为待开通账号(3)
            if (application.Status != 3)
            {
                result.Message = "只有待开通账号的申请才能完成设置";
                return new JsonResult(result);
            }
            
            // 调用服务完成账号设置
            result = await _venuesServer.SetupVenueAccountAsync(dto, application.ApplicationID);
            return new JsonResult(result);
        }

        /// <summary>
        /// 获取当前用户入驻的球馆信息(功能预留后期在做扩展 球馆的操作要在后台操作 要功能分明)
        /// </summary>
        [HttpGet("my-venue")]
        [Authorize]
        public async Task<JsonResult> GetMyVenue()
        {
            var result = new ApiResult<VenueInfoDto> { Success = false };
            
            // 从Token中获取用户ID
            string? idClaim = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Sid))?.Value;
            if (idClaim.IsNullOrWhiteSpace())
            {
                result.Message = "无权限，请登录";
                return new JsonResult(result);
            }
            int userId = (int)idClaim.ToInt32();
            
            // 获取与用户关联的球馆信息
            var venueApplication = await _venueApplicationsServer.QueryAsync(a => a.CreatedByUserID == userId && a.Status == 5);
            if (venueApplication == null || venueApplication.VenunId == null)
            {
                result.Message = "您尚未成功入驻球馆";
                return new JsonResult(result);
            }
            
            // 查询球馆详细信息
            var venue = await _venuesServer.QueryAsync(v => v.VenueID == venueApplication.VenunId);
            if (venue == null)
            {
                result.Message = "球馆信息不存在";
                return new JsonResult(result);
            }
            
            // 构建返回数据
            result.Data = new VenueInfoDto
            {
                VenueId = venue.VenueID,
                VenueName = venue.VenueName,
                Images = venue.Images,
                OpenTime = venue.OpenTime.ToString(),
                CloseTime = venue.CloseTime.ToString(),
                Address = venue.Address,
                ContactPhone = venue.ContactPhone,
                ManagerName = venue.ManagerName,
                Description = venue.Description,
                ReservationRules = venue.ReservationRules,
                Province = venue.Province,
                City = venue.City,
                Zone = venue.Zone
            };
            
            result.Success = true;
            result.Message = "获取球馆信息成功";
            
            return new JsonResult(result);
        }
    }
} 